﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace OrderGeneratorService
{
    public partial class OrderGeneratorService : ServiceBase
    {
        Generator gen;
        Order order;
        string mktPrice;
        IPAddress groupAddress;
        IPEndPoint mcastEP;
        Socket mdpSocket;
        Socket mdcSocket;
        byte[] sendBuffer;
        byte[] receiveBuffer;
        IPEndPoint localEP;

        public Order OrderGenerator(string ServiceName, string orderType, int NumOfContract, double Price, int BuySell)
        {
            InitializeComponent();
            gen = new Generator();
            order = gen.generateOrder("FIRE");
            return order;
        }

        public void MultiSend(string data)
        {
           //IP Multicast address
           groupAddress = IPAddress.Parse("224.5.6.7");
           mcastEP = new IPEndPoint(groupAddress, 30002);
           mdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
           sendBuffer = new byte[512];
           sendBuffer = Encoding.ASCII.GetBytes(mktPrice);

           //Set multicast TTL
           mdpSocket.SetSocketOption(SocketOptionLevel.IP,
                               SocketOptionName.MulticastTimeToLive, 3);
           //Send data to multicast address
           mdpSocket.SendTo(sendBuffer, mcastEP);
           mdpSocket.Close();
           Console.WriteLine("Market Data sent to group of consumers");
           Console.ReadLine();
        }

        protected override void OnStart(string[] args)
        {
           localEP = new IPEndPoint(IPAddress.Loopback, 20000);
           Console.WriteLine("Market-Data Producer Service Started - (Using MultiCast)");
           Console.WriteLine("Waiting for service input ... ");
           mdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           mdpSocket.Bind(localEP);
           mdpSocket.Listen(10);
           mdcSocket = mdpSocket.Accept();
           EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
           int bytesReceived = mdpSocket.ReceiveFrom(receiveBuffer, ref endPoint);
           IPEndPoint mdpEndPoint = (IPEndPoint)endPoint;
           string ser = Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived);


           order = gen.generateOrder(ser);
           mktPrice = order.ToString();
           Console.WriteLine(mktPrice);


        }

        protected override void OnStop()
        {
        }

        protected override void OnContinue()
        {
        }
    }
}
